﻿using System;

namespace ComplexNumberRepresentation
{
    class ComplexNumber
    {
        private double a;
        private double b;

        public ComplexNumber(double a, double b = 0)
        {
            this.a = a;
            this.b = b;
        }

        public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
        {
            double a = c1.a + c2.a;
            double b = c1.b + c2.b;
            return new ComplexNumber(a, b);
        }

        public static ComplexNumber operator -(ComplexNumber c1, ComplexNumber c2)
        {
            double a = c1.a - c2.a;
            double b = c1.b - c2.b;
            return new ComplexNumber(a, b);
        }

        public static ComplexNumber operator *(ComplexNumber c1, ComplexNumber c2)
        {
            double a = c1.a * c2.a - c1.b * c2.b;
            double b = c1.b * c2.a + c1.a + c2.b;
            return new ComplexNumber(a, b);
        }

        public static ComplexNumber operator /(ComplexNumber c1, ComplexNumber c2)
        {
            double denominator = c2.a * c2.a + c2.b * c2.b;
            double a = (c1.a * c2.a + c1.b * c2.b) / denominator;
            double b = (c1.b * c2.a - c1.a * c2.b) / denominator;
            return new ComplexNumber(a, b);
        }

        public double this[int index]
        {
            get
            {
                switch (index)
                {
                    case 0:
                        return a;
                    case 1:
                        return b;
                    default:
                        throw new ArgumentException(index + "is not a valid index.");
                }
            }
        }

        public static implicit operator ComplexNumber(double n)
        {
            return new ComplexNumber(n);
        }

        public static explicit operator double(ComplexNumber c)
        {
            if (c.b != 0)
            {
                throw new ArgumentException(
                    string.Format("\nCannot convert ({0}) to double.", c.ToString()));
            }
            return c.a;
        }

        public override string ToString()
        {
            string toString;
            if (b == 0)
            {
                toString = a.ToString();
            }
            else
            {
                toString = string.Format("{0} + {1}i", a, b);
            }
            return toString;
        }
    }
}
